package com.aote.model;

import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;
import com.browsesoft.Tools;
import com.browsesoft.baseadapter.HTMLBasicTableModel;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLFormModel;
import com.browsesoft.htmlcomponent.HTMLTableComponent;
import com.browsesoft.util.ComponentHelper;

/**
 * 进行数据批量更新的模型
 */
public class BatchUpdateModel implements HTMLFormModel {
	// 要进行批量更新的输入框，<Element>
	private Collection inputs = new LinkedList();

	// 要进行批量更新的表名
	private String table;

	// 要进行批量更新的对象id号
	private String ids;

	public void init(HttpServletRequest request) throws Exception {
		// 找到要进行批量更新的组件
		HTMLBasicComponent basic = ComponentHelper.getComponent(request);
		HTMLTableComponent comp = (HTMLTableComponent) com.aote.util.ComponentHelper
				.getChildComponent(basic, HTMLTableComponent.class);
		HTMLBasicTableModel model = (HTMLBasicTableModel) comp.getModel();
		Collection c = model.getChanged();
		this.ids = Tools.LinkedListTostring(new LinkedList(c));
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 提交时，根据输入框内容批量更新
		String action = request.getParameter("action");
		if (action != null && action.equals("confirm")) {
			this.doBatchUpdate(request);
		}
	}

	/**
	 * 执行批量更新
	 */
	private void doBatchUpdate(HttpServletRequest request) {
		String sets = this.getSetValues(request);
		String sql = "update " + table + " set " + sets + " where id in(" + ids
				+ ")";
		try {
			DBTools.excuteUpdate(sql);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 组织sql语句set部分
	 */
	private String getSetValues(HttpServletRequest request) {
		Collection result = new LinkedList();
		Iterator iter = this.inputs.iterator();
		while (iter.hasNext()) {
			// 组织一个赋值段
			Element e = (Element) iter.next();
			String name = e.getAttribute("name");
			String value = (String) request.getParameter(name);
			String seg = name + "='" + value + "'";
			result.add(seg);
		}
		// 把所有赋值段组织成","分隔的字符串
		String str = Tools.iteratorToString(result.iterator());
		return str;
	}

	public void setComponent(HTMLBasicComponent component) {
		// 得到表名
		Element e = component.getElement();
		this.table = e.getAttribute("table");
		this.inputs = ExtendElement.findElementsOfAttr(e, "fieldtype");
	}

	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	public void updateAttributes(Hashtable ht) throws Exception {
	}

	public Hashtable getAttributes() throws Exception {
		return new Hashtable();
	}

	public Iterator getOptions(String name) throws Exception {
		return null;
	}
}
